#include "qipadresseditor.h"

#include "../../shared/property/qabstractproperty.h"
#include "../../shared/host/qabstracthost.h"
#include "../../shared/qpropertyfactory.h"

#include <QPainter>
#include <QKeyEvent>

QIpAddressEditor::QIpAddressEditor(QAbstractProperty *property, QUndoStack *stack, QWidget *parent) :
    QAbstractSpinBox(parent),
    m_property(property),
    m_current_index(0)
{
    setAddress(m_property->get_value().toInt());
    connect(lineEdit(),SIGNAL(textChanged(QString)),this,SLOT(edit_text_changed(QString)));
}

QIpAddressEditor::~QIpAddressEditor()
{
}

void QIpAddressEditor::keyPressEvent(QKeyEvent *event)
{
    bool select = true;
    bool inserted = false;

    switch (event->key())
    {
    case Qt::Key_Enter:
    case Qt::Key_Return:
        event->ignore();
        emit editingFinished();
        return;
    default:
        if (event->key()>=Qt::Key_0 && event->key()<=Qt::Key_9)
        {
            inserted = select = !event->text().isEmpty() && event->text().at(0).isPrint()
                       && !(event->modifiers() & ~(Qt::ShiftModifier|Qt::KeypadModifier));
            break;
        }
    case Qt::Key_Left:
    case Qt::Key_Right:
        if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right)
        {
            if (!(event->modifiers() & Qt::ControlModifier))
            {
                select = false;
                break;
            }
        }
    case Qt::Key_Backtab:
    case Qt::Key_Tab:
        {
        event->accept();

        const bool forward = event->key() != Qt::Key_Left && event->key() != Qt::Key_Backtab
                             && (event->key() != Qt::Key_Tab || !(event->modifiers() & Qt::ShiftModifier));
        if (event->key() != Qt::Key_Backtab && event->key() != Qt::Key_Tab)
            focusNextPrevChild(forward);

        return;
        }
    }
    QAbstractSpinBox::keyPressEvent(event);
}

void QIpAddressEditor::setAddress(int address)
{
    if(m_ipAddress!=address)
    {
        m_ipAddress=address;
        m_property->emit_edit_value(address);
        update_value();
    }
}

int QIpAddressEditor::address()
{
    return m_ipAddress;
}

void QIpAddressEditor::update_value()
{
    lineEdit()->setText(QString("%1.%2.%3.%4")
                        .arg((m_ipAddress>>24)&0xff)
                        .arg((m_ipAddress>>16)&0xff)
                        .arg((m_ipAddress>>8)&0xff)
                        .arg(m_ipAddress&0xff));
}

void QIpAddressEditor::edit_text_changed(const QString &t)
{
    QStringList list=t.split(".");
    if(list.size()!=4)
    {
        return;
    }

    int v=((list.at(0).toInt()&0xff)<<24)+
            ((list.at(1).toInt()&0xff)<<16)+
            ((list.at(2).toInt()&0xff)<<8)+
            (list.at(3).toInt()&0xff);
    setAddress(v);
}

qRegisterPropertyEditor(IPAdress,QIpAddressEditor)
